package org.fast.project.dao.po;

import com.fasterxml.jackson.annotation.JsonIgnore;

import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import jakarta.persistence.PostLoad;
import jakarta.persistence.PostPersist;
import jakarta.persistence.PostUpdate;
import jakarta.persistence.PrePersist;
import jakarta.persistence.PreUpdate;
import jakarta.persistence.Transient;
import lombok.Data;

import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.domain.Persistable;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;

/**
 * @author : lilith·bristol
 * @program : spring-web-archetype-po
 * @description : 基础持久化类 所以具体业务持久化对象都应继承此类
 * 包含有默认属性 用于JPA自动审计
 * @date : 2020-04-28 22:55
 **/

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Data
public abstract class BaseEntity<ID> implements Persistable<ID> {

    @Transient
    private boolean isNew = true;

    @Override
    public boolean isNew() {
        return isNew;
    }

    @PostLoad
    void markNotNew() {
        this.isNew = false;
    }

    @JsonIgnore
    @Transient
    String entityName = this.getClass().getSimpleName();

    /**
     * 创建者
     */
    @CreatedBy
    String createdBy;
    /**
     * 最后修改者
     */
    @LastModifiedBy
    String modifiedBy;

    /**
     * 实体创建时间
     */
    @Column(name = "create_time", nullable = false)
    @CreatedDate
    protected LocalDateTime createTime = LocalDateTime.now();

    /**
     * 实体修改时间
     */
    @Column(name = "update_time", nullable = false)
    @LastModifiedDate
    protected LocalDateTime updateTime = LocalDateTime.now();

    /**
     * 持久化存储前操作
     */
    @PrePersist
    public void prePersist() {
        this.markNotNew();
        this.setCreatedBy("current user");
        this.setModifiedBy("current user");
        this.setCreateTime(LocalDateTime.now());
        this.setUpdateTime(LocalDateTime.now());
    }

    /**
     * 持久化存储后操作
     */
    @PostPersist
    public void postPersist() {
    }


    /**
     * 更新前操作
     */
    @PreUpdate
    public void preUpdate() {
        this.setModifiedBy("current user");
        this.setUpdateTime(LocalDateTime.now());
    }

    /**
     * 更新后操作
     */
    @PostUpdate
    public void postUpdate() {

    }
}
